//
//  OLLocrAPIContext.m
//
// Copyright (c) 2009 Houdah Software s.à r.l. (http://www.houdah.com)
// Copyright (c) 2009 Lukhnos D. Liu (http://lukhnos.org)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//

#import "OLLocrAPIContext.h"

#import "OLLocrAPIRequest.h"


NSString *const OLLocrThumbnailSize					= @"_T";
NSString *const OLLocrSquareSize					= @"_SQ";
NSString *const OLLocrSmallSize						= @"_S";
NSString *const OLLocrMediumSize					= @"_M";
NSString *const OLLocrLargeSize						= @"_L";
NSString *const OLLocrOriginalSize					= @"";


#define kDefaultLocrQueryEndpoint				@"http://www.locr.com/api/"
#define kDefaultLocrSignatureEndpoint			@"http://www.locr.com/api/get_api_signature.php"
#define kDefaultLocrUploadEndpoint				@"http://www.locr.com/api/post_photo_xml.php"

@implementation OLLocrAPIContext

- (void)dealloc
{
    [userName release], userName = nil;
    [password release], password = nil;
    
    [queryEndpoint release], queryEndpoint = nil;
    [signatureEndpoint release], signatureEndpoint = nil;
    [uploadEndpoint release], uploadEndpoint = nil;
    
	[httpRequest release], httpRequest = nil;
	
    [super dealloc];
}

- (id)initWithUserName:(NSString *)inUserName password:(NSString *)inPassword
{
    if (self = [super init]) {
        userName = [inUserName copy];
        password = [inPassword copy];
        
        queryEndpoint = [kDefaultLocrQueryEndpoint copy];
        signatureEndpoint = [kDefaultLocrSignatureEndpoint copy];
        uploadEndpoint = [kDefaultLocrUploadEndpoint copy];

		httpRequest = [[LFHTTPRequest alloc] init];
		
        [httpRequest setContentType:nil];
        [httpRequest setDelegate:self];
	}
	
	return self;
}

+ (NSURL *)photoSourceURLFromDictionary:(NSDictionary *)inDictionary size:(NSString *)inSizeModifier
{
	NSDictionary *attributes = [inDictionary olAttributes];
	NSString *path = [attributes objectForKey:@"path"];
	NSString *name = [attributes objectForKey:@"name"];
	NSString *extension = [attributes objectForKey:@"ext"];
	NSString *photoURLString = [NSString stringWithFormat:@"%@%@%@.%@", path, name, inSizeModifier, extension, nil];
	
	return [NSURL URLWithString:photoURLString];
}

+ (NSURL *)photoWebPageURLFromDictionary:(NSDictionary *)inDictionary
{
	NSDictionary *photoURLDictionary = [inDictionary valueForKeyPath:@"photo_url"];
	NSString *photoURLString = [photoURLDictionary olTextContent];
	
	return [NSURL URLWithString:photoURLString];
}

- (NSString*)userName
{
	return userName;
}

- (NSString*)password
{
	return password;
}

- (void)setQueryEndpoint:(NSString *)inEndpoint
{
    NSString *tmp = queryEndpoint;
    queryEndpoint = [inEndpoint copy];
    [tmp release];
}

- (NSString *)queryEndpoint
{
    return queryEndpoint;
}

- (void)setSignatureEndpoint:(NSString *)inEndpoint
{
    NSString *tmp = signatureEndpoint;
    signatureEndpoint = [inEndpoint copy];
    [tmp release];
}

- (NSString *)signatureEndpoint
{
    return signatureEndpoint;
}

- (void)setUploadEndpoint:(NSString *)inEndpoint
{
    NSString *tmp = uploadEndpoint;
    uploadEndpoint = [inEndpoint copy];
    [tmp release];
}

- (NSString *)uploadEndpoint
{
    return uploadEndpoint;
}

#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
@synthesize userName;
@synthesize password;
#endif

- (BOOL)requestSignature:(id<OLLocrAPISignatureConsumer>)signatureConsumer
{
    if ([httpRequest isRunning]) {
        return NO;
    }
    
	[httpRequest setSessionInfo:signatureConsumer];
	
	return [httpRequest performMethod:LFHTTPRequestGETMethod onURL:[NSURL URLWithString:signatureEndpoint] withData:nil];
}


#pragma mark -
#pragma mark LFHTTPRequest delegate methods

- (void)httpRequestDidComplete:(LFHTTPRequest *)request
{
	NSData *data = [request receivedData];
	NSString *signature = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
	id<OLLocrAPISignatureConsumer> signatureConsumer = [request sessionInfo];
	
	[signatureConsumer context:self providesSignature:signature];
}

- (void)httpRequest:(LFHTTPRequest *)request didFailWithError:(NSString *)errorString
{
	id<OLLocrAPISignatureConsumer> signatureConsumer = [request sessionInfo];
	
	if (errorString == nil) {
		errorString = NSLocalizedString(@"Failure to acquire API signature",
										@"Failure to acquire API signature");
	}
	
	NSError *error = [NSError errorWithDomain:OLLocrAPIRequestErrorDomain
										 code:OLLocrAPIRequestConnectionError
									 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:errorString, NSLocalizedFailureReasonErrorKey, nil]];
	
	[signatureConsumer context:self failedToProvideSignatureWithError:error];
}

@end